package videoCapture;

import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.Timer;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameRecorder.Exception;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.OpenCVFrameRecorder;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class JavaCVTest {
//	public static void main(String[] args) throws Exception, java.lang.Exception {
//		OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
//        grabber.start();
//        IplImage grabbedImage = grabber.grab();
//
//        CanvasFrame canvasFrame = new CanvasFrame("Cam");
//        canvasFrame.setCanvasSize(grabbedImage.width(), grabbedImage.height());
//
//        System.out.println("framerate = " + grabber.getFrameRate());
//        grabber.setFrameRate(grabber.getFrameRate());
//        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("test",  grabber.getImageWidth(),grabber.getImageHeight());
//
//        recorder.setVideoCodec(13);
//        recorder.setFormat("mp4");
//        recorder.setPixelFormat(avutil.PIX_FMT_BGR32);
//        recorder.setFrameRate(30);
//        recorder.setVideoBitrate(10 * 1024 * 1024);
//
//        recorder.start();
//        while (canvasFrame.isVisible() && (grabbedImage = grabber.grab()) != null) {
//            canvasFrame.showImage(grabbedImage);
//            recorder.record(grabbedImage);
//        }
//        recorder.stop();
//        grabber.stop();
//        canvasFrame.dispose();
//
//	}
	
public static String savedImageFile = "c:\\tmp\\my.jpg";
	
	//timer for image capture animation
	static class TimerAction implements ActionListener {
		private Graphics2D g;
		private CanvasFrame canvasFrame;
		private int width,height;
		
		private int delta=10;
		private int count = 0;
		
		private Timer timer;
		public void setTimer(Timer timer){
			this.timer = timer;
		}
		 
		public TimerAction(CanvasFrame canvasFrame){
			this.g = (Graphics2D)canvasFrame.getCanvas().getGraphics();	
			this.canvasFrame = canvasFrame;
			this.width = canvasFrame.getCanvas().getWidth();
			this.height = canvasFrame.getCanvas().getHeight();
		}
        public void actionPerformed(ActionEvent e) {
        	int offset = delta*count;
        	if(width-offset>=offset && height-offset >= offset) {        
        		g.drawRect(offset, offset, width-2*offset, height-2*offset);
        		canvasFrame.repaint();
                count++;
        	}else{
        		//when animation is done, reset count and stop timer.
        		timer.stop();
        		count = 0;
        	}            
        }
    }

	public static void main(String[] args) throws Exception, java.lang.Exception {
		//open camera source
		OpenCVFrameGrabber grabber = new OpenCVFrameGrabber("test.avi");
		OpenCVFrameRecorder recorder;
		grabber.start();
		
		//create a frame for real-time image display
		CanvasFrame canvasFrame = new CanvasFrame("Camera");
		IplImage image = grabber.grab();
		int width = image.width();
		int height = image.height();
		
		recorder = new OpenCVFrameRecorder("test.avi", width, height);
		
        canvasFrame.setCanvasSize(width, height);
        canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //onscreen buffer for image capture
        final BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D bGraphics = bImage.createGraphics();     
        
        //animation timer
        TimerAction timerAction = new TimerAction(canvasFrame);
		final Timer timer=new Timer(10, timerAction);
		timerAction.setTimer(timer);
		 
		//click the frame to capture an image
        canvasFrame.getCanvas().addMouseListener(new MouseAdapter(){
        	public void mouseClicked(MouseEvent e){     
        		timer.start(); //start animation
        		try {
					ImageIO.write(bImage, "jpg", new File(savedImageFile));
				} catch (IOException e1) {
					e1.printStackTrace();
				}	        		
            }        	     
        });
        
        //real-time image display
        recorder.start();
        int i = 0;
        while(canvasFrame.isVisible() && (image=grabber.grab()) != null){
  //      	if(!timer.isRunning()) { //when animation is on, pause real-time display
	        	canvasFrame.showImage(image);	
	        	//draw the onscreen image simutaneously
	        	bGraphics.drawImage(image.getBufferedImage(),null,0,0);  
	        	recorder.record(image);
  //      	}
	        	if(i++ > 300)
	        		break;
	        	System.out.println(i);
        }
        recorder.stop();
        //release resources
  //      cvReleaseImage(image);	 
        grabber.stop();
        canvasFrame.dispose();
	}
}
